package com.common.util;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

	private static PoolingHttpClientConnectionManager connMgr;
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 30000;
	private static Map<String, RequestConfig> timeOutConf = new HashMap<String,RequestConfig>();

	static {
		// 设置连接池
		//long st,ed;
		//st = System.currentTimeMillis();
		connMgr = new PoolingHttpClientConnectionManager();
		// 设置连接池大小
		connMgr.setMaxTotal(100);
		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		// configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();
		//ed = System.currentTimeMillis();
		//System.out.println("init :"+(ed-st));
	}

	/**
	 * 
	 * @param reqURL
	 * @param connectTimeout 单位 毫秒
	 * @param readTimeout 单位 毫秒
	 * @return
	 * @throws Exception
	 */
	public static boolean setTimeOut(String reqURL, Integer connectTimeout, Integer readTimeout) throws Exception {
		if (reqURL == null || "".equals(reqURL.trim())) {
			return false;
		}
		if (timeOutConf.containsKey(reqURL)) {
			return false;
		}
		if (connectTimeout == null) {
			connectTimeout = MAX_TIMEOUT;
		}
		if (readTimeout == null) {
			readTimeout = MAX_TIMEOUT;
		}
		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(connectTimeout);
		// 设置读取超时
		configBuilder.setSocketTimeout(readTimeout);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		// configBuilder.setStaleConnectionCheckEnabled(true);
		RequestConfig requestConfig = configBuilder.build();
		timeOutConf.put(reqURL, requestConfig);
		return true;
	}

	private HttpClientUtil() {
	}
	
	public static String sendGetRequest(String reqURL) throws Exception {
		return sendGetRequest(null, reqURL, "UTF-8");
	}

	public static String sendGetRequest(String timeOutKey, String reqURL) throws Exception {
		return sendGetRequest(timeOutKey, reqURL, "UTF-8");
	}

	/**
	 * 发送HTTP_GET请求
	 * 
	 * @see 该方法会自动关闭连接,释放资源
	 * @param requestURL
	 *            请求地址(含参数)
	 * @param decodeCharset
	 *            解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendGetRequest(String timeOutKey, String reqURL, String decodeCharset) throws Exception {
		String responseContent = null; // 响应内容
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet
		try {
			if (timeOutKey !=null&& timeOutConf.containsKey(timeOutKey)) {
				httpGet.setConfig(timeOutConf.get(timeOutKey));
			} else {
				httpGet.setConfig(requestConfig);
			}
			response = httpClient.execute(httpGet); // 执行GET请求
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
			}
			//Header[] allHeaders = response.getAllHeaders();
//			for (Header head : allHeaders) {
//				System.out.println(head.getName());
//				System.out.println(URLDecoder.decode(head.getValue(), "UTF-8"));
//				System.out.println(new String(head.getValue().getBytes("UTF-8"), "UTF-8"));
//			}
			// System.out.println("请求地址: " + httpGet.getURI());
			// System.out.println("响应状态: " + response.getStatusLine());
			// System.out.println("响应长度: " + responseLength);
			// System.out.println("响应内容: " + responseContent);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			if (response != null) {
				response.close();
			}
			httpClient.close();
		}
		return responseContent;
	}

	public static String sendPostRequest(String reqURL, String sendData) throws Exception {
		return sendPostRequest(reqURL, sendData, null, false, null, null);
	}

	public static String sendPostRequest(String reqURL, String sendData, Map<String, String> header) throws Exception {
		if (sendData == null) {
			sendData = "";
		}
		return sendPostRequest(reqURL, sendData, header, false, null, null);
	}

	/**
	 * 发送HTTP_POST请求
	 * 
	 * @see 该方法为
	 *      <code>sendPostRequest(String,String,boolean,String,String)</code>
	 *      的简化方法
	 * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
	 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
	 *      ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
	 * @param isEncoder
	 *            用于指明请求数据是否需要UTF-8编码,true为需要
	 */
	public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) throws Exception {
		return sendPostRequest(reqURL, sendData, null, isEncoder, null, null);
	}

	/**
	 * 发送HTTP_POST请求
	 * 
	 * @see 该方法会自动关闭连接,释放资源
	 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
	 *      ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @param reqURL
	 *            请求地址
	 * @param sendData
	 *            请求参数,若有多个参数则应拼接成param11=value11&param22=value22&param33=value33的形式后,
	 *            传入该参数中
	 * @param isEncoder
	 *            请求数据是否需要encodeCharset编码,true为需要
	 * @param encodeCharset
	 *            编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
	 * @param decodeCharset
	 *            解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendPostRequest(String reqURL, String sendData, Map<String, String> header, boolean isEncoder,
			String encodeCharset, String decodeCharset) throws Exception {
		String responseContent = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(reqURL);
		httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		try {
			if (header != null && header.size() > 0) {
				for (String headerName : header.keySet()) {
					httpPost.setHeader(headerName, header.get(headerName));
				}
			}
			httpPost.setConfig(requestConfig);
			if (isEncoder) {
				List<NameValuePair> formParams = new ArrayList<NameValuePair>();
				for (String str : sendData.split("&")) {
					formParams.add(new BasicNameValuePair(str.substring(0, str.indexOf("=")),
							str.substring(str.indexOf("=") + 1)));
				}
				httpPost.setEntity(new StringEntity(
						URLEncodedUtils.format(formParams, encodeCharset == null ? "UTF-8" : encodeCharset)));
			} else {
				httpPost.setEntity(new StringEntity(sendData, "UTF-8"));
			}
			//httpClient.getParams().setParameter("http.socket.timeout", new Integer(30000));
			response = httpClient.execute(httpPost);
			
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				if (null != entity) {
					responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
					EntityUtils.consume(entity);
				}
			} else {
				throw new Exception(
						"http response status is not 200,returned status is:" + response.getStatusLine().getStatusCode()
								+ ",msg:" + response.getStatusLine().getReasonPhrase());
			}

		} catch (Exception e) {
			throw new Exception(e);
			// LogUtil.getLogger().error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下",
			// e);
		} finally {
			if (response != null) {
				response.close();
			}
			httpClient.close();
		}
		return responseContent;
	}

	public static String sendPostRequest(String reqURL, Map<String, String> params, Map<String, String> header)
			throws Exception {
		return sendPostRequest(reqURL, params, header, null, null);
	}

	public static String sendPostRequest(String reqURL, Map<String, String> params) throws Exception {
		return sendPostRequest(reqURL, params, null, null, null);
	}

	/**
	 * 发送HTTP_POST请求
	 * 
	 * @see 该方法会自动关闭连接,释放资源
	 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行
	 *      <code>URLEncoder.encode(string,encodeCharset)</code>
	 * @param reqURL
	 *            请求地址
	 * @param params
	 *            请求参数
	 * @param encodeCharset
	 *            编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
	 * @param decodeCharset
	 *            解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendPostRequest(String reqURL, Map<String, String> params, Map<String, String> header,
			String encodeCharset, String decodeCharset) throws Exception {
		String responseContent = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(reqURL);
		List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
		for (Map.Entry<String, String> entry : params.entrySet()) {
			formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		try {
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset == null ? "UTF-8" : encodeCharset));
			if (header != null && header.size() > 0) {
				for (String headerName : header.keySet()) {
					httpPost.setHeader(headerName, header.get(headerName));
				}
			}

			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity);
			}
		} catch (Exception e) {
			throw new Exception(e);
			// LogUtil.getLogger().error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下",
			// e);
		} finally {
			if (response != null) {
				response.close();
			}
			httpClient.close();
		}
		return responseContent;
	}

	public static String doPostSSL(String apiUrl, String params) {
		return doPostSSL(apiUrl, params, null);
	}

	/**
	 * 发送 SSL POST 请求（HTTPS），JSON形式
	 * 
	 * @param apiUrl
	 *            API接口URL
	 * @param json
	 *            JSON对象
	 * @return
	 */
	public static String doPostSSL(String apiUrl, String sendData, Map<String, String> header) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new StringEntity(sendData, "UTF-8"));
			if (header != null && header.size() > 0) {
				for (String headerName : header.keySet()) {
					httpPost.setHeader(headerName, header.get(headerName));
				}
			}
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 创建SSL安全连接
	 * 
	 * @return
	 */
	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
		SSLConnectionSocketFactory sslsf = null;
		//SSLConnectionSocketFactory ss=new SSLConnectionSocketFactory(sslContext, hostnameVerifier)
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

				@Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
				
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			});
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		return sslsf;
	}
	//
	// /**
	// * 发送HTTP_POST请求
	// *
	// * @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文
	// * <code>URLEncoder.encode(string,encodeCharset)</code>
	// * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
	// * @param reqURL
	// * 请求地址
	// * @param params
	// * 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
	// * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
	// * 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
	// */
	// public static String sendPostRequestByJava(String reqURL, Map<String,
	// String> params) throws Exception {
	// StringBuilder sendData = new StringBuilder();
	// for (Map.Entry<String, String> entry : params.entrySet()) {
	// sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
	// }
	// if (sendData.length() > 0) {
	// sendData.setLength(sendData.length() - 1); // 删除最后一个&符号
	// }
	// return sendPostRequestByJava(reqURL, sendData.toString());
	// }
	//
	// /**
	// * 发送HTTP_POST请求
	// *
	// * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文
	// * <code>URLEncoder.encode(string,encodeCharset)</code>
	// * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
	// * @param reqURL
	// * 请求地址
	// * @param sendData
	// * 发送到远程主机的正文数据
	// * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
	// * 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
	// */
	// public static String sendPostRequestByJava(String reqURL, String
	// sendData) throws Exception {
	// HttpURLConnection httpURLConnection = null;
	// OutputStream out = null; // 写
	// InputStream in = null; // 读
	// int httpStatusCode = 0; // 远程主机响应的HTTP状态码
	// try {
	// URL sendUrl = new URL(reqURL);
	// httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
	// httpURLConnection.setRequestMethod("POST");
	// httpURLConnection.setDoOutput(true); // 指示应用程序要将数据写入URL连接,其值默认为false
	// httpURLConnection.setUseCaches(false);
	// httpURLConnection.setConnectTimeout(30000); // 30秒连接超时
	// httpURLConnection.setReadTimeout(30000); // 30秒读取超时
	//
	// out = httpURLConnection.getOutputStream();
	// out.write(sendData.toString().getBytes());
	//
	// // 清空缓冲区,发送数据
	// out.flush();
	//
	// // 获取HTTP状态码
	// httpStatusCode = httpURLConnection.getResponseCode();
	//
	// // 该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
	// // 若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
	// // respData = httpURLConnection.getResponseMessage();
	//
	// // //处理返回结果
	// // BufferedReader br = new BufferedReader(new
	// // InputStreamReader(httpURLConnection.getInputStream()));
	// // String row = null;
	// // String respData = "";
	// // if((row=br.readLine()) != null){
	// // //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
	// // respData = row; //HTTP协议POST方式的最后一行数据为正文数据
	// // }
	// // br.close();
	//
	// in = httpURLConnection.getInputStream();
	// byte[] byteDatas = new byte[in.available()];
	// in.read(byteDatas);
	// return new String(byteDatas) + "`" + httpStatusCode;
	// } catch (Exception e) {
	// e.printStackTrace();
	// // throw new Exception(e);
	// // LogUtil.getLogger().error(e.getMessage());
	// return "Failed`" + httpStatusCode;
	// } finally {
	// if (out != null) {
	// try {
	// out.close();
	// } catch (Exception e) {
	// throw new Exception(e);
	// // LogUtil.getLogger().error("关闭输出流时发生异常,堆栈信息如下", e);
	// }
	// }
	// if (in != null) {
	// try {
	// in.close();
	// } catch (Exception e) {
	// throw new Exception(e);
	// // LogUtil.getLogger().error("关闭输入流时发生异常,堆栈信息如下", e);
	// }
	// }
	// if (httpURLConnection != null) {
	// httpURLConnection.disconnect();
	// httpURLConnection = null;
	// }
	// }
	// }

	public static void main(String[] args) {
		try {
			Map<String, String> header = new HashMap<String, String>();
			header.put("Content-Type", "application/json");
			String reqMsg = "{\"body\":{},\"head\":{\"sign\":\"\",\"appId\":\"54654654\",\"remark\":\"remark\"}}";
			String reqURL = "http://localhost:7080/WebTest/func/ws/query";
			// String fileContext =
			// HttpClientUtil.sendPostRequest(reqURL,reqMsg,header);
			//byte[] responseContent = null;
			String responseContent = null;
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = null;
			HttpPost httpPost = new HttpPost(reqURL);
			httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
			try {
				if (header != null && header.size() > 0) {
					for (String headerName : header.keySet()) {
						httpPost.setHeader(headerName, header.get(headerName));
					}
				}
				httpPost.setConfig(requestConfig);
				httpPost.setEntity(new StringEntity(reqMsg));
				response = httpClient.execute(httpPost);
				HttpEntity entity = response.getEntity();
				if (null != entity) {
					//responseContent = EntityUtils.toByteArray(entity);
					responseContent = EntityUtils.toString(entity, "UTF-8");
					EntityUtils.consume(entity);
				}
			} catch (Exception e) {
				throw new Exception(e);
				// LogUtil.getLogger().error("与[" + reqURL +
				// "]通信过程中发生异常,堆栈信息如下",
				// e);
			} finally {
				if (response != null) {
					response.close();
				}
				httpClient.close();
			}
//			System.out.println(responseContent);
			/*File file = new File("D:\\test\\file.dbf");
			// byte bt[] = fileContext.getBytes("UTF-8");
			FileOutputStream in = new FileOutputStream(file);
			try {
				in.write(responseContent, 0, responseContent.length);
				in.close();
				// boolean success=true;
				// System.out.println("写入文件成功");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
